package com.seed.auth.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seed.auth.entity.TAuthUser;
import com.seed.auth.service.UserService;

@Controller
public class UserController {

    @Autowired
    private UserService userServiceImpl;

    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            // 捕获密码错误异常
            model.addAttribute("message", "username or password error!");
            return "error";
        } catch (UnknownAccountException uae) {
            // 捕获未知用户名异常
            model.addAttribute("message", "username or password error!");
            return "error";
        } catch (ExcessiveAttemptsException eae) {
            // 捕获错误登录过多的异常
            model.addAttribute("message", "times error");
            return "error";
        }
        TAuthUser user = userServiceImpl.findByUsername(username);
        subject.getSession().setAttribute("user", user);
        return "success";
    }

}
